package com.android.dialer.extendboard;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Message;
import android.os.RemoteException;
import android.service.notification.StatusBarNotification;
import android.telecom.CallAudioState;

import com.android.dialer.main.impl.MainActivity;
import com.android.dialer.util.CallUtil;
import com.android.dialer.util.DialerUtils;
import com.android.incallui.audiomode.AudioModeProvider;
import com.android.incallui.call.CallList;
import com.android.incallui.call.DialerCall;
import com.android.incallui.call.TelecomAdapter;
import com.google.gson.Gson;
import com.android.dialer.common.LogUtil;


public class KeyEventHandler {
    private static final String TAG = "KeyEventHandler";
    private ControllerService context;
    private List<String> clientMessengerKeys;
    private Map<String, ISmallControllerCallback> clientMessengerMap;

    protected class UsbKeyEvent {
        public int keyCode;
        public int keyState;
        public UsbKeyEvent(USBMessage usbMessage) {
            ByteBuffer buffer = ByteBuffer.wrap(usbMessage.getData()).order(ByteOrder.LITTLE_ENDIAN);
            // dump buffer into hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < buffer.capacity(); i++) {
                sb.append(String.format("%02X ", buffer.get(i)));
            }
            LogUtil.i(TAG, "UsbKeyEvent: buffer: " + sb.toString());

            buffer = ByteBuffer.wrap(usbMessage.getData()).order(ByteOrder.LITTLE_ENDIAN);
            this.keyCode = buffer.getInt();
            this.keyState = buffer.getInt();

            LogUtil.i(TAG, "UsbKeyEvent: keyCode: " + keyCode + " keyState: " + keyState);
        }
    }

    public KeyEventHandler(ControllerService context) {
        this.context = context;
        clientMessengerKeys = new ArrayList<>();
        clientMessengerMap = new HashMap<String, ISmallControllerCallback>();
    }

    public void registerMessenger(ISmallControllerCallback callback, String key) {
        LogUtil.i(TAG, "=============================>>>>>>>>>>>>>registerMessenger: clientMessengers size: " + clientMessengerMap.size());
        if (clientMessengerMap.containsKey(key)) {
            LogUtil.i(TAG, "=============================>>>>>>>>>>>>>registerMessenger: clientMessengers already contains key: " + key);

            // make this key in the last one of clientMessengerKeys
            // find the index of key, not using indexOf method
            int index = -1;
            for (int i = 0; i < clientMessengerKeys.size(); i++) {
                if (clientMessengerKeys.get(i).equals(key)) {
                    index = i;
                    break;
                }
            }
            if (index != -1) {
                clientMessengerKeys.remove(index);
                clientMessengerKeys.add(key);
            }

            return;
        }else {
            LogUtil.i(TAG, "=============================>>>>>>>>>>>>>registerMessenger: clientMessengers not contains key: " + key);
        }

        clientMessengerMap.put(key, callback);
        clientMessengerKeys.add(key);
    }

    public void unregisterMessenger(String key) {
        LogUtil.i(TAG, "=============================>>>>>>>>>>>>>unregisterMessenger: clientMessengers size: " + clientMessengerMap.size());

        int index = -1;
        for (int i = 0; i < clientMessengerKeys.size(); i++) {
            if (clientMessengerKeys.get(i).equals(key)) {
                index = i;
                break;
            }
        }

        if (clientMessengerMap.containsKey(key)) {
            LogUtil.i(TAG, "=============================>>>>>>>>>>>>>unregisterMessenger: clientMessengers contains key: " + key);
            clientMessengerMap.remove(key);
        } else {
            LogUtil.i(TAG, "=============================>>>>>>>>>>>>>unregisterMessenger: clientMessengers not contains key: " + key);
        }

        if (index != -1) {
            clientMessengerKeys.remove(index);
        }

    }


    private void openDialActivity(int keyCode, int keyState) {
        /**
         * when keyCode is SM_HOOK_OFF_KEY, keyState only have Pressed and Released, like Handsfree
         */

        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri uri = new Uri.Builder().scheme("key")
                .appendQueryParameter("keyCode", String.valueOf(keyCode))
                .appendQueryParameter("keyState", String.valueOf(keyState))
                .build();
        intent.setData(uri);

        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        context.getApplicationContext().startActivity(intent);
    }

    public void turnOnOrOffHwPower() {
        String nodePath = "/sys/devices/platform/soc/soc:ap-apb/200f0000.i2c/i2c-2/2-001b/hwpower";
        // read the file first
        try {
            String result = new String(Files.readAllBytes(Paths.get(nodePath)));
            LogUtil.i(TAG, "turnOnOrOffHwPower: result: " + result);
            // write the file
            if (result.contains("power=0")) {
                Files.write(Paths.get(nodePath), "1".getBytes(), StandardOpenOption.WRITE);
            } else {
                Files.write(Paths.get(nodePath), "0".getBytes(), StandardOpenOption.WRITE);
            }
        } catch (Exception e) {
            LogUtil.e(TAG, "turnOnOrOffHwPower: error turning on or off hw power", e);
        }

    }

    private void sendMessage(int eventType, int arg1, int arg2) {
        // 发送按键事件
        if (clientMessengerMap.isEmpty()) {
            LogUtil.i(TAG, "sendKey: clientMessengerMap is empty");
            return;
        }

        LogUtil.i(TAG, "handleKeyEvent: arg1: " + arg1 + " arg2: " + arg2);
        LogUtil.i(TAG, "count of clientMessengers: " + clientMessengerMap.size());
        ISmallControllerCallback clientMessenger = null;
        Message message = Message.obtain(null, eventType, arg1, arg2);
        // 确保从列表中获取的 Messenger 是有效的
        String key = clientMessengerKeys.getLast();
        clientMessenger = clientMessengerMap.get(key);
        try {
            if (clientMessenger != null) {
                clientMessenger.onMessageReceived(message);
            }
        } catch (RemoteException e) {
            LogUtil.e(TAG, "KeyEventHandler: send message failed", e);

            // 检查是否是 DeadObjectException 并移除无效的 Messenger
            if (e.toString().contains("DeadObjectException")) {
                LogUtil.i(TAG, "KeyEventHandler: clientMessenger is dead, unregistering");
                clientMessengerMap.remove(key);
                clientMessengerKeys.remove(key);
            }
        }
        // send usbMessage to the device
    }

    public void handleHookStateInd(USBMessage usbMessage) {
        // 处理挂钩状态指示
        ByteBuffer buffer = ByteBuffer.wrap(usbMessage.getData()).order(ByteOrder.LITTLE_ENDIAN);
        int hookState = buffer.getInt();
        sendMessage(ServiceConstant.MSG_HOOK_EVENT_TYPE, hookState, 0);
    }

    private boolean isCallInComing() {
        DialerCall call = CallList.getInstance().getIncomingCall();
        LogUtil.i(TAG, "isCallInComing: call: " + call);
        return call != null;
    }

    private boolean hasActiveCallOrBackgroudCall() {
        DialerCall call = CallList.getInstance().getActiveOrBackgroundCall();
        LogUtil.i(TAG, "isInCall: call: " + call);
        return call != null;
    }

    private boolean hasOutgoingCall() {
        DialerCall call = CallList.getInstance().getPendingOutgoingCall();
        if (call == null) {
            call = CallList.getInstance().getOutgoingCall();
        }

        return call != null;
    }

    // true for answer, false fot reject
    private void processIncommingCall(boolean answerOrReject) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
            if (notification.getId() == 1) {
                Notification ntf = notification.getNotification();
                if (ntf != null && ntf.actions != null) {
                    for (Notification.Action action : ntf.actions) {
                        String actionTitle = action.title.toString();
                        String expectedTitle = answerOrReject
                                ? context.getText(R.string.notification_action_answer).toString()
                                : context.getText(R.string.notification_action_dismiss).toString();
                        LogUtil.i(TAG, "processIncommingCall: actionTitle: " + actionTitle + " expectedTitle: " + expectedTitle);
                        if (actionTitle.equals(expectedTitle)) {
                            try {
                                LogUtil.i(TAG, "handleKeyEvent: action: " + actionTitle);
                                action.actionIntent.send();
                            } catch (PendingIntent.CanceledException e) {
                                LogUtil.e(TAG, "handleKeyEvent: error sending pending intent", e);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    private void processHandsFreeAction() {
        AudioModeProvider audioModeProvider = AudioModeProvider.getInstance();
        String expectedTitle = null;

        if (audioModeProvider != null) {
            LogUtil.i(TAG, "processIncommingCall: audioModeProvider: " + audioModeProvider.getAudioState().getRoute());

            if (audioModeProvider.getAudioState().getRoute() == CallAudioState.ROUTE_SPEAKER) {
                expectedTitle = context.getText(R.string.notification_action_speaker_off).toString();
            }else if (audioModeProvider.getAudioState().getRoute() == CallAudioState.ROUTE_EARPIECE) {
                expectedTitle = context.getText(R.string.notification_action_speaker_on).toString();
            }

            if (expectedTitle != null) {
                NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
                    if (notification.getId() == 1) {
                        Notification ntf = notification.getNotification();
                        if (ntf != null && ntf.actions != null) {
                            for (Notification.Action action : ntf.actions) {
                                String actionTitle = action.title.toString();
                                LogUtil.i(TAG, "processIncommingCall: actionTitle: " + actionTitle + " expectedTitle: " + expectedTitle);
                                if (actionTitle.equals(expectedTitle)) {
                                    try {
                                        LogUtil.i(TAG, "handleKeyEvent: action: " + actionTitle);
                                        action.actionIntent.send();
                                    } catch (PendingIntent.CanceledException e) {
                                        LogUtil.e(TAG, "handleKeyEvent: error sending pending intent", e);
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void switchToEearpiece() {
        AudioModeProvider audioModeProvider = AudioModeProvider.getInstance();
        if (audioModeProvider != null) {
            if (audioModeProvider.getAudioState().getRoute() == CallAudioState.ROUTE_SPEAKER) {
                TelecomAdapter.getInstance().setAudioRoute(CallAudioState.ROUTE_WIRED_OR_EARPIECE);
            }
        }
    }


    private void hangupCallInCall() {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
            if (notification.getId() == 1) {
                Notification ntf = notification.getNotification();

                if (ntf != null && ntf.actions != null) {
                    for (Notification.Action action : ntf.actions) {
                        String actionTitle = action.title.toString();
                        String expectedTitle = context.getText(R.string.notification_action_end_call).toString();
                        LogUtil.i(TAG, "handleKeyEvent: actionTitle: " + actionTitle + " expectedTitle: " + expectedTitle);
                        if (actionTitle.equals(expectedTitle)) {
                            try {
                                LogUtil.i(TAG, "handleKeyEvent: action: " + actionTitle);
                                action.actionIntent.send();
                            } catch (PendingIntent.CanceledException e) {
                                LogUtil.e(TAG, "handleKeyEvent: error sending pending intent", e);
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    private void sendContentIntentOfNotification() {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        for (StatusBarNotification notification : notificationManager.getActiveNotifications()) {
            if (notification.getId() == 1) {
                Notification ntf = notification.getNotification();
                if (ntf != null && ntf.contentIntent != null) {
                    try {
                        ntf.contentIntent.send();
                    } catch (PendingIntent.CanceledException e) {
                        LogUtil.e(TAG, "handleKeyEvent: error sending pending intent", e);
                    }
                    break;
                }
            }
        }
    }

    public void handleKeyEvent(USBMessage usbMessage) {
        UsbKeyEvent keyEvent = new UsbKeyEvent(usbMessage);
        int keyCode = keyEvent.keyCode;
        int keyState = keyEvent.keyState;

        switch (keyCode) {
            // 处理Dial按键
            case ServiceConstant.SM_P12_KEY_DIAL: {
                if (clientMessengerMap.isEmpty()) {
                    // 无界面的时候来电和电话中，需要特殊对待
                    if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                        if (isCallInComing()) {
                            // 接听
                            processIncommingCall(true);
                        } else if (hasActiveCallOrBackgroudCall() || hasOutgoingCall()) {
                            // 打开通话界面
                            sendContentIntentOfNotification();
                        } else {
                            // 打开拨号界面
                            openDialActivity(keyCode, keyState);
                        }
                    }
                }else {
                    // 有界面的时候，直接发送消息
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            // 处理Hangup事件
            case ServiceConstant.SM_P13_KEY_HANGUP: {
                if (clientMessengerMap.isEmpty()) {
                    // 无界面的时候来电和电话中，需要特殊对待
                    if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                        if (isCallInComing()) {
                            // 挂断
                            processIncommingCall(false);
                        } else if (hasActiveCallOrBackgroudCall() || hasOutgoingCall()) {
                            // 挂断
                            hangupCallInCall();
                        }
                    }
                } else {
                    // 有界面的时候，直接发送消息
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            // 处理HandsFree事件
            case ServiceConstant.SM_P11_KEY_HANDSFREE: {
                if (clientMessengerMap.isEmpty()) {
                    // 无界面的时候来电和电话中，需要特殊对待
                    if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                        if (hasActiveCallOrBackgroudCall() || hasOutgoingCall()) {
                            // 打开通话界面
                            processHandsFreeAction();
                        } else {
                            // 打开拨号界面
                            openDialActivity(keyCode, keyState);
                        }
                    }
                }else {
                    // 有界面的时候，直接发送消息
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            case ServiceConstant.SM_HOOK_KEY: {
                if (clientMessengerMap.isEmpty()) {
                    if (isCallInComing()) {
                        if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                            // send broadcast to answer the call
                            context.switchMic(1);
                            processIncommingCall(true);
                        }
                    }else if (hasActiveCallOrBackgroudCall() || hasOutgoingCall()) {
                        if (keyState == ServiceConstant.SM_KEY_STATE_PRESSED) {
                            // send broadcast to hangup the call
                            context.switchMic(0);
                            hangupCallInCall();
                        }else if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                            context.switchMic(1);
                            switchToEearpiece();
                        }
                    }else {
                        // open dial activity
                        if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                            // open dial activity
                            context.switchMic(1);
                            openDialActivity(keyCode, keyState);
                        }
                    }
                }else {
                    // 有界面的时候，直接发送消息
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            case ServiceConstant.SM_CALL_ADD:
            case ServiceConstant.SM_CALL_HOLD:
            case ServiceConstant.SM_CALL_MERGE:
            case ServiceConstant.SM_CALL_SWAP:
            case ServiceConstant.SM_ONBOARD_MUTE: {
                if (!clientMessengerMap.isEmpty()) {
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            case ServiceConstant.SM_P00_KEY_2:
            case ServiceConstant.SM_P01_KEY_1:
            case ServiceConstant.SM_P02_KEY_4:
            case ServiceConstant.SM_P03_KEY_5:
            case ServiceConstant.SM_P04_KEY_7:
            case ServiceConstant.SM_P05_KEY_8:
            case ServiceConstant.SM_P06_KEY_STAR:
            case ServiceConstant.SM_P07_KEY_0:
            case ServiceConstant.SM_P14_KEY_POUND:
            case ServiceConstant.SM_P15_KEY_9:
            case ServiceConstant.SM_P16_KEY_6:
            case ServiceConstant.SM_P17_KEY_3: {
                LogUtil.i(TAG, "handleKeyEvent: is clientMessenger empty: " + clientMessengerMap.isEmpty());
                if (clientMessengerMap.isEmpty()) {
                    openDialActivity(keyCode, keyState);
                } else {
                    sendMessage(ServiceConstant.MSG_KEY_EVENT_TYPE, keyCode, keyState);
                }
            }
            break;

            case ServiceConstant.SM_P10_KEY_POWER: {
                // 投影开关
                if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                    turnOnOrOffHwPower();
                }
            }
            break;

            case ServiceConstant.SM_P02_KEY_TRAPEZOID_MINUS:
                // 梯形校正
                break;
            case ServiceConstant.SM_P03_KEY_TRAPEZOID_PLUS:
                // 梯形校正
                break;
            case ServiceConstant.SM_ONBOARD_M1:
            case ServiceConstant.SM_ONBOARD_M2:
            case ServiceConstant.SM_P06_KEY_M5:
            case ServiceConstant.SM_P07_KEY_M4:
            case ServiceConstant.SM_P10_KEY_M3: {
                if (keyState == ServiceConstant.SM_KEY_STATE_RELEASED) {
                    int keyindex = 0;
                    ContentResolver contentResolver = context.getContentResolver();

                    if (keyCode == ServiceConstant.SM_ONBOARD_M1) {
                        keyindex = 1;
                    } else if (keyCode == ServiceConstant.SM_ONBOARD_M2) {
                        keyindex = 2;
                    } else if (keyCode == ServiceConstant.SM_P10_KEY_M3) {
                        keyindex = 3;
                    } else if (keyCode == ServiceConstant.SM_P07_KEY_M4) {
                        keyindex = 4;
                    } else {
                        keyindex = 5;
                    }

                    LogUtil.i(TAG, "handleKeyEvent: keyindex: " + keyindex);

                    String[] args = {String.valueOf(keyindex)};
                    try (Cursor cursor = contentResolver.query(PhonesContentProvider.CONTENT_URI, null, "", args, null)) {
                        if (cursor != null && cursor.moveToFirst()) {
                            String value = cursor.getString(cursor.getColumnIndex(PhonesContentProvider.COLUMN_VALUE));
                            SpeedDialItem item = new Gson().fromJson(value, SpeedDialItem.class);
                            LogUtil.i(TAG, "handleKeyEvent: item: " + item.toString());
                            if (item.isActive()) {
                                final Intent intent = new Intent(Intent.ACTION_CALL, CallUtil.getCallUri(item.getNumber()));
                                DialerUtils.startActivityWithErrorToast(context.getApplicationContext(), intent);
                            } else {
                                // open SpeedDialActivity
                                Intent intent = new Intent(context.getApplicationContext(), SpeedDialActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.getApplicationContext().startActivity(intent);
                            }
                        }
                    } catch (Exception e) {
                        LogUtil.e(TAG, "handleKeyEvent: error querying content resolver", e);
                    }
                }
            }
            break;
        }
    }
}
